package com.yourbatis.interpreter;

import com.yourbatis.syntax.FunStatement;
import com.yourbatis.syntax.FunctionObject;

import java.util.HashMap;
import java.util.Map;

public class Environment {
    private static Scope currentScope = new Scope(null);
    private static final Map<String, FunctionObject> functions = new HashMap<>();
    private static Object returnValue;
    public static void enterScope() {
        currentScope = new Scope(currentScope);
    }

    public static void exitScope() {
        if (currentScope.getParent() == null) {
            throw new RuntimeException("无法退出全局作用域");
        }
        currentScope = currentScope.getParent();
    }

    public static void define(String name, Object value) {
        currentScope.define(name, value);
    }

    public static void assign(String name, Object value) {
        currentScope.assign(name, value);
    }

    public static Object get(String name) {
        return currentScope.get(name);
    }



    public static boolean contains(String name) {
        return currentScope.contains(name);
    }

    // 函数管理
    public static void defineFun(String name, FunctionObject function) {
        if (functions.containsKey(name)) {
            throw new RuntimeException("Function already defined: " + name);
        }
        functions.put(name, function);
    }

    public static FunctionObject getFun(String name) {
        if (!functions.containsKey(name)) {
            throw new RuntimeException("Undefined function: " + name);
        }
        return functions.get(name);
    }

    // 返回值管理
    public static void setReturnValue(Object value) {
        returnValue = value;
    }

    public static Object getReturnValue() {
        return returnValue;
    }

    public static void init(Map map){
        if(map != null){
            currentScope.init(map);
        }
    }
}
